"""
RAG检索器
提供智能检索和匹配功能
"""

import logging
from typing import List, Dict, Any, Optional
from .vector_store import VectorStore
from .embeddings import Embeddings

logger = logging.getLogger(__name__)

class RAGRetriever:
    """RAG检索器类"""
    
    def __init__(self, vector_store: VectorStore):
        """
        初始化检索器
        
        Args:
            vector_store: 向量数据库实例
        """
        self.vector_store = vector_store
        self.embeddings = vector_store.embeddings
        
        logger.info("RAG检索器初始化成功")
    
    def retrieve_job_matches(self, resume_content: str, n_results: int = 5) -> List[Dict[str, Any]]:
        """
        为简历检索匹配的职位
        
        Args:
            resume_content: 简历内容
            n_results: 返回结果数量
            
        Returns:
            匹配的职位列表
        """
        try:
            # 从简历中提取关键信息
            key_info = self._extract_key_info(resume_content)
            
            # 构建搜索查询
            query = self._build_job_query(key_info)
            
            # 搜索职位
            job_matches = self.vector_store.search_jobs(query, n_results)
            
            # 计算匹配度
            for job in job_matches:
                job['match_score'] = self._calculate_job_match_score(resume_content, job['content'])
            
            # 按匹配度排序
            job_matches.sort(key=lambda x: x['match_score'], reverse=True)
            
            return job_matches
            
        except Exception as e:
            logger.error(f"职位匹配检索失败: {str(e)}")
            raise
    
    def retrieve_skill_matches(self, resume_content: str, n_results: int = 10) -> List[Dict[str, Any]]:
        """
        从简历中检索相关技能
        
        Args:
            resume_content: 简历内容
            n_results: 返回结果数量
            
        Returns:
            相关技能列表
        """
        try:
            # 构建技能搜索查询
            query = self._build_skill_query(resume_content)
            
            # 搜索技能
            skill_matches = self.vector_store.search_skills(query, n_results)
            
            # 计算相关性分数
            for skill in skill_matches:
                skill['relevance_score'] = self._calculate_skill_relevance(resume_content, skill['content'])
            
            # 按相关性排序
            skill_matches.sort(key=lambda x: x['relevance_score'], reverse=True)
            
            return skill_matches
            
        except Exception as e:
            logger.error(f"技能匹配检索失败: {str(e)}")
            raise
    
    def retrieve_similar_resumes(self, resume_content: str, n_results: int = 5) -> List[Dict[str, Any]]:
        """
        检索相似的简历
        
        Args:
            resume_content: 简历内容
            n_results: 返回结果数量
            
        Returns:
            相似简历列表
        """
        try:
            # 搜索相似简历
            similar_resumes = self.vector_store.search_resumes(resume_content, n_results)
            
            # 计算相似度
            for resume in similar_resumes:
                resume['similarity_score'] = 1 - resume['distance']  # 距离转换为相似度
            
            return similar_resumes
            
        except Exception as e:
            logger.error(f"相似简历检索失败: {str(e)}")
            raise
    
    def _extract_key_info(self, resume_content: str) -> Dict[str, Any]:
        """
        从简历内容中提取关键信息
        
        Args:
            resume_content: 简历内容(字符串或字典)
            
        Returns:
            关键信息字典
        """
        # 处理输入类型
        if isinstance(resume_content, dict):
            content = resume_content.get('resume_data', '')
        else:
            content = str(resume_content)
        
        # 简单的关键词提取（后续可以用更复杂的NLP方法）
        import re
        
        key_info = {
            'skills': [],
            'experience': [],
            'education': [],
            'technologies': []
        }
        
        # 提取技能关键词
        skill_patterns = [
            r'技能[：:]\s*(.+)',
            r'技术栈[：:]\s*(.+)',
            r'熟练掌握[：:]\s*(.+)',
            r'熟悉[：:]\s*(.+)'
        ]
        
        for pattern in skill_patterns:
            matches = re.findall(pattern, resume_content)
            key_info['skills'].extend(matches)
        
        # 提取技术关键词
        tech_keywords = [
            'Python', 'Java', 'JavaScript', 'Vue', 'React', 'Node.js',
            'MySQL', 'MongoDB', 'Redis', 'Docker', 'Kubernetes',
            '机器学习', '深度学习', '数据分析', '前端', '后端'
        ]
        
        for keyword in tech_keywords:
            if keyword in resume_content:
                key_info['technologies'].append(keyword)
        
        return key_info
    
    def _build_job_query(self, key_info: Dict[str, Any]) -> str:
        """
        构建职位搜索查询
        
        Args:
            key_info: 关键信息
            
        Returns:
            搜索查询字符串
        """
        query_parts = []
        
        # 添加技能
        if key_info['skills']:
            query_parts.extend(key_info['skills'])
        
        # 添加技术栈
        if key_info['technologies']:
            query_parts.extend(key_info['technologies'])
        
        # 组合查询
        query = " ".join(query_parts)
        
        # 如果查询为空，使用通用查询
        if not query.strip():
            query = "软件开发 技术 编程"
        
        return query
    
    def _build_skill_query(self, resume_content: str) -> str:
        """
        构建技能搜索查询
        
        Args:
            resume_content: 简历内容(字符串或字典)
            
        Returns:
            搜索查询字符串
        """
        # 处理输入类型
        if isinstance(resume_content, dict):
            content = resume_content.get('resume_data', '')
        else:
            content = str(resume_content)
        
        # 提取简历中的技术相关词汇
        import re
        
        # 常见技术词汇模式
        tech_patterns = [
            r'\b[A-Z][a-z]+(?:\.js|\.py|\.net|\.com)\b',  # 技术名称
            r'\b(?:Python|Java|JavaScript|Vue|React|Angular|Node|Django|Flask|Spring)\b',
            r'\b(?:MySQL|MongoDB|Redis|PostgreSQL|Oracle)\b',
            r'\b(?:Docker|Kubernetes|Git|Linux|AWS|Azure|GCP)\b'
        ]
        
        skills = []
        for pattern in tech_patterns:
            matches = re.findall(pattern, resume_content)
            skills.extend(matches)
        
        # 添加中文技能词汇
        chinese_skills = [
            '前端开发', '后端开发', '全栈开发', '数据分析', '机器学习',
            '深度学习', '人工智能', '数据库设计', '系统架构', '项目管理'
        ]
        
        for skill in chinese_skills:
            if skill in resume_content:
                skills.append(skill)
        
        query = " ".join(skills)
        
        # 如果查询为空，使用通用查询
        if not query.strip():
            query = "编程 开发 技术"
        
        return query
    
    def _calculate_job_match_score(self, resume_content: str, job_content: str) -> float:
        """
        计算简历与职位的匹配度
        
        Args:
            resume_content: 简历内容
            job_content: 职位内容
            
        Returns:
            匹配度分数 (0-1)
        """
        try:
            # 生成向量
            resume_embedding = self.embeddings.embed_text(resume_content)
            job_embedding = self.embeddings.embed_text(job_content)
            
            # 计算余弦相似度
            similarity = self.embeddings.similarity(resume_embedding, job_embedding)
            
            return similarity
            
        except Exception as e:
            logger.error(f"计算职位匹配度失败: {str(e)}")
            return 0.0
    
    def _calculate_skill_relevance(self, resume_content: str, skill_content: str) -> float:
        """
        计算技能相关性
        
        Args:
            resume_content: 简历内容
            skill_content: 技能内容
            
        Returns:
            相关性分数 (0-1)
        """
        try:
            # 生成向量
            resume_embedding = self.embeddings.embed_text(resume_content)
            skill_embedding = self.embeddings.embed_text(skill_content)
            
            # 计算余弦相似度
            relevance = self.embeddings.similarity(resume_embedding, skill_embedding)
            
            return relevance
            
        except Exception as e:
            logger.error(f"计算技能相关性失败: {str(e)}")
            return 0.0
    
    def get_retrieval_stats(self) -> Dict[str, Any]:
        """获取检索统计信息"""
        try:
            stats = self.vector_store.get_collection_stats()
            stats['total_documents'] = sum(stats.values())
            return stats
        except Exception as e:
            logger.error(f"获取检索统计失败: {str(e)}")
            raise
